﻿using amis6_api.Dto;
using amis6_api.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace amis6_api.Utils
{
    public class RecursiveUtil
    {

        public static List<CatalogDto> GetCatalogDtos(List<Catalog> list)
        {
            var parent = list.Where(a => a.Catalog_Father == null).ToList();
            List<CatalogDto> catalogs = new List<CatalogDto>();
            foreach (var item in parent)
            {
                CatalogDto catalogDto = new CatalogDto(item);
                catalogs.Add(catalogDto);
                AddChild(catalogDto, list);
            }
            return catalogs;
        }

        private static void AddChild(CatalogDto catalogDto, List<Catalog> list)
        {
            if (list.All(a => a.Catalog_Father != catalogDto.Parent.Catalog_ID))
                return;
            else
            {
                var children = list.Where(a => a.Catalog_Father == catalogDto.Parent.Catalog_ID).ToList();
                catalogDto.Children = new List<CatalogDto>();
                foreach (var item in children)
                {
                    CatalogDto childDto = new CatalogDto(item);

                    catalogDto.Children.Add(childDto);

                    AddChild(childDto, list);
                }
            }
        }

        public static List<SmallCatalogDto> GetSmallCatalogDto(List<SmallCatalog> list)
        {
            var parent = list.Where(a => a.Catalog_Father == null).ToList();
            List<SmallCatalogDto> catalogs = new List<SmallCatalogDto>();
            foreach (var item in parent)
            {
                SmallCatalogDto catalogDto = new SmallCatalogDto(item);
                catalogs.Add(catalogDto);
                AddChild(catalogDto, list);
            }
            return catalogs;
        }

        private static void AddChild(SmallCatalogDto catalogDto, List<SmallCatalog> list)
        {
            if (list.All(a => a.Catalog_Father != catalogDto.Parent.Catalog_ID))
                return;
            else
            {
                var children = list.Where(a => a.Catalog_Father == catalogDto.Parent.Catalog_ID).ToList();
                catalogDto.Children = new List<SmallCatalogDto>();
                foreach (var item in children)
                {
                    SmallCatalogDto childDto = new SmallCatalogDto(item);

                    catalogDto.Children.Add(childDto);

                    AddChild(childDto, list);
                }
            }
        }
    }
}
